<!--安全-特种设备-待检特种设备  作废了-->
<template>
	<Layout>
		<Form ref="queryForm" :model="dataToQuery" :label-width="120">
			<Row v-show="!switchFlag" class="query-form">
				<Col span="8">
				<FormItem label="企业名称：" prop="order">
					<cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName'
						:orgTree="true" :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}">
					</cascader-dom>
				</FormItem>
				</Col>
				<Col span="8">
				<FormItem label="填表时间：" prop="content">
					<DatePicker class="query-form-el" v-model="dataToQuery.dateRange" format="yyyy-MM-dd"
						type="daterange" placement="bottom-end" placeholder="请选择查询时间段"
						@on-change="onSelectQueryDateRange"></DatePicker>
				</FormItem>
				</Col>
				<Col span="8">
				<Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
				<Button @click="reset" class="ivu-btn-reset">重置</Button>
				<Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
				</Col>
			</Row>
			<Row v-show="switchFlag" class="query-form">
				<Col span="8">
				<FormItem label="企业名称：" prop="order">
					<cascader-dom class="query-form-el" ref='queryOrgCascader1' @setOrgInfo='setQueryCompanyName'
						:orgTree="true" :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}">
					</cascader-dom>
				</FormItem>
				</Col>
				<Col span="8">
				<FormItem label="填表时间：" prop="content">
					<DatePicker class="query-form-el" v-model="dataToQuery.dateRange" format="yyyy-MM-dd"
						type="daterange" placement="bottom-end" placeholder="请选择查询时间段"
						@on-change="onSelectQueryDateRange"></DatePicker>
				</FormItem>
				</Col>
				<Col span="8">
				<FormItem label="设备名称：" prop="eqName">
					<Input v-model='dataToQuery.eqName' class="query-form-el"></Input>
				</FormItem>
				</Col>
			</Row>
			<Row v-show="switchFlag" class="query-form">
				<Col span="8">
				<FormItem label="制造单位：" prop="manufacture">
					<Input v-model='dataToQuery.manufacture' class="query-form-el"></Input>
				</FormItem>
				</Col>
				<Col span="8">
				</Col>
				<Col span="8" offset="8">
				<Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
				<Button @click="reset" class="ivu-btn-reset">重置</Button>
				<Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
				</Col>
			</Row>
			<Row class="query-form">
				<Col span="24">
				<Button type="primary" class="ivu-btn-add" icon="md-cloud-download" :loading="buttonLoading"
					@click="exportFormSubmit">导出</Button>
				</Col>
			</Row>
		</Form>
		<Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
			:loading='pageStatus.loading' border :columns="columns1" :data="dataTable" :row-class-name="rowClassName">
		</Table>
		<Row style="margin-right:10px;">
			<Col span="24">
			<Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
				@on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
				show-elevator />
			</Col>
		</Row>
		<Modal title="待检特种设备" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=800
			:styles="{height:'684px'}" class-name='limit-height-dialog'>
			<Row>
				<Col span="24">
				<Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'rpt-form'" :show-message="false"
					:model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?160:null"
					:label-position="mode === 'view'?'right':'top'">
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="23">
						<FormItem label='企业名称：' prop='companyId'>
							<div v-if="mode === 'view'">{{dataToView.companyName}}</div>
							<cascader-dom v-else ref='orgCascader' @setOrgInfo='setCompanyId'
								@setOrgname="setCompanyName" :orgTree="true" :currentOrgId="dataToView.companyId"
								:setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}">
							</cascader-dom>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label='所在地：' prop='companyAddress'>
							<div v-if="mode === 'view'">{{areaCodeToAreaName(dataToView.companyAddress)}}</div>
							<Cascader v-else :data="tempAreaTree" v-model="dataToView.companyAddressArr" change-on-select :transfer="true"
									  :load-data="areaTreeLoadData" :render-format="labels=>labels.join('·')"  :clearable='false'
									  @on-change="(value,selectedData)=>{$set(dataToView,'companyAddress',value.join(','))}"></Cascader>
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label='设备名称：' prop='eqName'>
							<div v-if="mode === 'view'">{{dataToView.eqName}}</div>
							<Input v-else type='text' v-model='dataToView.eqName'></Input>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="23">
						<FormItem label='规格型号：' prop='eqModel'>
							<div v-if="mode === 'view'">{{dataToView.eqModel}}</div>
							<Input v-else type='text' v-model='dataToView.eqModel'></Input>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="23">
						<FormItem label='制造单位：' prop='manufacture'>
							<div v-if="mode === 'view'">{{dataToView.manufacture}}</div>
							<Input v-else type='text' v-model='dataToView.manufacture'></Input>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label='产品合格证号：' prop='certificationNum'>
							<div v-if="mode === 'view'">{{dataToView.certificationNum}}</div>
							<Input v-else type='text' v-model='dataToView.certificationNum'></Input>
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label='使用许可证号：' prop='licenceNum'>
							<div v-if="mode === 'view'">{{dataToView.licenceNum}}</div>
							<Input v-else type='text' v-model='dataToView.licenceNum'></Input>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label='设备注册证号：' prop='registerNum'>
							<div v-if="mode === 'view'">{{dataToView.registerNum}}</div>
							<Input v-else type='text' v-model='dataToView.registerNum'></Input>
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label='投用日期：' prop='startDate'>
							<div v-if="mode === 'view'">{{renderViewDate(dataToView.startDate)}}</div>
							<DatePicker v-else type="date" placeholder="请选择日期" style="width: 100%"
								v-model='dataToView.startDate'></DatePicker>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="23">
						<FormItem label="安装位置：" prop="coordSite">
							<div v-if="mode === 'view'">{{dataToView.coordSite}}</div>
							<Input v-else type="text" v-model="dataToView.coordSite"></Input>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="23">
						<FormItem label="使用状况：" prop="useStatus">
							<div v-if="mode === 'view'">{{dataToView.useStatus}}</div>
							<Input v-else type="text" v-model="dataToView.useStatus"></Input>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label='定检日期：' prop='examDate'>
							<div v-if="mode === 'view'">{{renderViewDate(dataToView.examDate)}}</div>
							<DatePicker v-else type="date" placeholder="请选择日期" style="width: 100%"
								v-model='dataToView.examDate'></DatePicker>
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label="检验周期：" prop="examCycle">
							<div v-if="mode === 'view'">
								{{this.examCycleList[dataToView.examCycle] && this.examCycleList[dataToView.examCycle].codingName}}
							</div>
							<Select v-else v-model="dataToView.examCycle">
								<Option v-for="item in examCycleList" :value="item.codingCodeId" :key="item.index"
									:label="item.codingName">
									{{item.codingName}}
								</Option>
							</Select>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="23">
						<FormItem label='检验结果：' prop='examResult'>
							<div v-if="mode === 'view'">{{dataToView.examResult}}</div>
							<Input v-else type='text' v-model='dataToView.examResult'></Input>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label='填表人：' prop='registrant'>
							<div v-if="mode === 'view'">{{dataToView.createUserName}}</div>
							<Input v-else type='text' v-model='dataToView.registrant' readonly></Input>
						</FormItem>
						</Col>
						<Col span="11">
						<FormItem label='填表时间：' prop='registTime'>
							<div v-if="mode === 'view'">{{renderViewDate(dataToView.createDate)}}</div>
							<DatePicker v-else type="date" placeholder="请选择日期" style="width: 100%" class="query-form-el"
								v-model='dataToView.registTime' readonly></DatePicker>
						</FormItem>
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="11">
						<FormItem label='填表人电话：' prop='createMobile'>
							<div v-if="mode === 'view'">{{dataToView.createMobile}}</div>
							<Input v-if="mode === 'add'" type='text' v-model='dataToView.createMobile'></Input>
							<Input v-if="mode === 'edit'" type='text' v-model='dataToView.createMobile'
								:readonly="this.currentUser.userId === dataToView.createUserId ? false : 'readonly'"></Input>
						</FormItem>
						</Col>
						<Col span="11">
						</Col>
					</Row>
					<Row type="flex" justify="space-around" class="code-row-bg">
						<Col span="23">
						<FormItem label='备注：' prop='notes'>
							<div v-if="mode === 'view'">{{dataToView.notes}}</div>
							<Input v-else type='textarea' v-model='dataToView.notes'></Input>
						</FormItem>
						</Col>
					</Row>
				</Form>
				</Col>
			</Row>
			<div slot="footer">
				<Button v-if="mode != 'view'" type="primary" class='ivu-btn-save'
					@click="submit('dialogForm')">确定</Button>
				<Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
				<Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
			</div>
		</Modal>
	</Layout>
</template>

<script>
	import {
		Api
	} from '@/api/index.js'
	import {
		formatDate
	} from '@/tools/index'
	import _deepclone from 'lodash/cloneDeep'
	import {
		mapState,
		mapGetters,
		mapActions
	} from 'vuex'
	var cascaderDom = () => import('@/components/cascader-dom.vue');
	import pageCommonFunction from '@/components/pageCommonFunction.js'
	import {
		sessionStorage
	} from '@/common/cacheUtils.js'
	export default {
		components: {
			cascaderDom
		},
		computed: {
			...mapState('trhg', {
				areaMap: state => state.area.areaMap ? state.area.areaMap : [],
                areaTreeMap: state => state.area.areaTreeMap?state.area.areaTreeMap:{},
			}),
		},
		data() {
			return {
				...this.createCommonDataField(),
				columns1: [{
						title: '序号',
						width: 80,
						fixed: 'left',
						align: 'center',
						render: this.indexColumnsRender
					},
					{
						key: 'eqName',
						title: '设备名称',
						align: 'center',
						fixed: 'left',
						width: 150
					},
					{
						key: 'categoryName',
						title: '设备类型',
						align: 'center',
						width: 150
					},
					{
						key: 'eqModel',
						title: '规格型号',
						align: 'center',
						width: 160
					},
					{
						key: 'companyName',
						title: '企业名称',
						align: 'center',
						width: 200
					},
					{
						key: 'companyAddress',
						title: '所在地',
						align: 'center',
						width: 120,
						render: this.renderCellArea
					},
					{
						key: 'manufacture',
						title: '制造单位',
						align: 'center',
						width: 150
					},
					{
						key: 'certificationNum',
						title: '产品合格证号',
						align: 'center',
						width: 140
					},
					{
						key: 'licenceNum',
						title: '使用许可证号',
						align: 'center',
						width: 150
					},
					{
						key: 'registerNum',
						title: '设备注册证号',
						align: 'center',
						width: 200
					},
					{
						key: 'startDate',
						title: '投用日期',
						align: 'center',
						width: 120,
						render: this.renderCellDate
					},
					{
						key: 'examDate',
						title: '定检日期',
						align: 'center',
						width: 120,
						render: this.renderCellDate
					},
					{
						key: 'examResult',
						title: '检验结果',
						align: 'center',
						width: 120,
						tooltip: true
					},
					{
						key: 'examCycle',
						title: '检验周期',
						align: 'center',
						width: 120,
						render: (h, params) => {
							return h('span', this.examCycleList && this.examCycleList[params.row.examCycle] && this
								.examCycleList[params.row.examCycle].codingName)
						},
					},
					{
						key: 'coordSite',
						title: '安装位置',
						align: 'center',
						width: 120,
						tooltip: true
					},
					{
						key: 'useStatus',
						title: '使用状况',
						align: 'center',
						width: 120,
						tooltip: true
					},
					{
						key: 'createDate',
						title: '填表时间',
						align: 'left',
						width: 120,
						render: this.renderCellDate
					},
					{
						key: 'notes',
						title: '备注',
						align: 'center',
						width: 120,
						tooltip: true
					},
					{
						title: '操作',
						key: 'action',
						fixed: 'right',
						width: 140,
						align: 'center',
						render: (h, params) => {
							let currentUser = JSON.parse(sessionStorage('userId').get('userId'));
							if (currentUser.loginId === this.Common.admin || currentUser.userId === params.row
								.createUserId || currentUser.userRole.find(obj => obj.roleId ==
									'73b38b37dff64392ba0ee7dd579bf293') != undefined) {
								return h('div', [
									h('A', {
										props: {
											type: 'primary',
											size: 'small'
										},
										style: {
											fontSize: '14px',
										},
										on: {
											click: () => {
												this.viewData(params);
											}
										}
									}, '详情'),
									h('Divider', {props: {type: 'vertical'}}, ''),
									h('A', {
									    props: {type: 'primary', size: 'small'},
									    disabled: true,
									    style: {fontSize: '14px'},
									    on: {
									        click: () => {
									            this.editData(params);
									        }
									    }
									}, '修改')
								]);
							}else{
								return h('div', [
								    h('A', {
								        props: {type: 'primary', size: 'small'},
								        style: {fontSize: '14px',},
								        on: {
								            click: () => {
								                this.viewData(params);
								            }
								        }
								    }, '详情'),
								    h('Divider', {props: {type: 'vertical'}}, ''),
								    h('A', {
								        props: {type: 'primary', size: 'small'},
								        style: {fontSize: '14px', color: '#c5c8ce'}
								    }, '修改')
								]);
							}
						}
					}
				],
				ruleCustom: {
					companyId: [{
						required: true,
						message: ' ',
						trigger: 'change'
					}],
					companyAddress: [{
						required: true,
						message: ' ',
						trigger: 'change'
					}],
					eqName: [{
						required: true,
						message: ' ',
						trigger: 'change'
					}],
					createMobile: [{
						pattern: /^((0\d{2,3}-\d{7,8})|(1[123456789]\d{9}))$/,
						required: true,
						message: ' ',
						trigger: 'change'
					}],
					examDate: [{
						validator: (rule, value, callback) => {
						    if (value == null || value == ''|| value == undefined) {
						        callback(' ')
						    } else {
						        callback()
						    }
						},
						required: true,
						message: ' ',
						trigger: 'change'
					}],
					examCycle: [{
						required: true,
						message: ' ',
						trigger: 'change'
					}],
				},
				tableHeight: 10,
				examCycleList: [],
				buttonLoading:false,
				// api
				queryUrl: Api.queryEqAccountPending,
				exportUrl: Api.exportEqAccountPending,
				updateUrl: Api.updateSafeRptSpecialEq
			}
		},
		async mounted() {
			this.setTableHeight();
			this.pageStatus.baseLoading = true
			await this.$store.dispatch('trhg/area/query', {scope: this}, {root: true})
			this.pageStatus.baseLoading = false
			await this.$http.get(Api.queryCodeDetailBySortId + '/IP-10001', {
				params: {}
			}).then((res) => {
				this.examCycleList = this.dictListToMap(res.data.data);
			});
			this.query();
            this.tempAreaTree = this.areaTreeMap['0']
		},
		methods: {
			...pageCommonFunction,
			createEmptyDataToAdd() {
				return {
					companyAddressArr: [],
					createMobile: sessionStorage('userId').getObject('userId').mobileNumber,
				}
			},
            beforeEditDialogOpen(data) {
                if(data.row.companyAddress){
                    data.row.companyAddressArr = data.row.companyAddress.split(',')
                    data.row.companyAddressName = this.areaCodeToAreaName(data.row.companyAddress)
                }
            },
            async afterDataToViewInit(data) {
                if (data && data.companyAddress) {
                    let companyAddressArr = data.companyAddress.split(',')
                    this.tempAreaTree = []
                    setTimeout(() => {
                        this.tempAreaTree = this.addressEditArr(this.areaTreeMap,companyAddressArr)
                    }, 100)
                }
            },
			deleteData(params) {
				this.deleteDateAjax(params);
			},
			query() {
				this.dataToView.listType = 2
				this.dataToQuery.orgId = sessionStorage('userId').getObject('userId').companyId
				this.queryAjax();
			},
			submit(name) {
				this.$set(this.dataToView, 'companyAddress', this.dataToView.companyAddressArr.join(','))
				this.submitAjax(name);
			},
			reset(){
				this.dataToQuery = {};
				if (this.$refs.queryOrgCascader) {
				    this.$refs.queryOrgCascader.resetCurrentOrg();
				}
				if (this.$refs.queryOrgCascader1) {
				    this.$refs.queryOrgCascader1.resetCurrentOrg();
				}
				this.pagedata.currentPage=1
				this.query()
			},
			rowClassName(row,index){
				var date = formatDate(new Date(),'yyyy-MM-dd')
				if(row.nextExamDate < date){
					return 'table-row-red';
				}
			},
			formatDate(date, fmt) {
			    if (/(y+)/.test(fmt)) {
			        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
			    }
			    let o = {
			        'M+': date.getMonth() + 1,
			        'd+': date.getDate(),
			        'h+': date.getHours(),
			        'm+': date.getMinutes(),
			        's+': date.getSeconds()
			    };
			    for (let k in o) {
			        if (new RegExp(`(${k})`).test(fmt)) {
			            let str = o[k] + '';
			            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
			        }
			    }
			    return fmt;
			},
			exportFormSubmit() {
				this.buttonLoading=true
				let orgId = sessionStorage('userId').getObject('userId').companyId
				let data = {
				    orgId:orgId,
				};
				data = Object.assign(data, JSON.parse(JSON.stringify(this.dataToQuery)));
				this.$http.get(Api.exportEqAccountPending, {
				    params:data,
				    responseType: 'blob'      //告诉服务器我们需要的响应格式
				}).then((res) => {
				    const aLink = document.createElement("a");
				    let blob = new Blob([res.data], {
				        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
				    });
				    aLink.href = URL.createObjectURL(blob)
				    aLink.download = "待检特殊设备("+ formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
				    aLink.click()
				    document.body.appendChild(aLink)
				    this.buttonLoading=false
				})
			}
		},
		watch: {},

	}
</script>

<style lang='css'>
	.rpt-form {}

	/deep/ .rpt-form .ivu-table-wrapper {
		overflow: visible;
	}

	/deep/ .rpt-form .ivu-table-wrapper .ivu-table {
		overflow: visible;
	}

	.ivu-table-tbody .table-row-red td{
	    background-color: #fedede !important;
	}
</style>
